<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Zend_Test_PHPUnit - Zend Framework Manual</title>

    <link href="../css/shCore.css" rel="stylesheet" type="text/css" />
    <link href="../css/shThemeDefault.css" rel="stylesheet" type="text/css" />
    <link href="../css/styles.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Zend Framework</h1>
<h2>Programmer's Reference Guide</h2>
<ul>
    <li><a href="../en/zend.test.phpunit.html">Inglês (English)</a></li>
    <li><a href="../pt-br/zend.test.phpunit.html">Português Brasileiro (Brazilian Portuguese)</a></li>
</ul>
<table width="100%">
    <tr valign="top">
        <td width="85%">
            <table width="100%">
                <tr>
                    <td width="25%" style="text-align: left;">
                    <a href="zend.test.introduction.html">Introduction</a>
                    </td>

                    <td width="50%" style="text-align: center;">
                        <div class="up"><span class="up"><a href="zend.test.html">Zend_Test</a></span><br />
                        <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div>
                    </td>

                    <td width="25%" style="text-align: right;">
                        <div class="next" style="text-align: right; float: right;"><a href="zend.test.phpunit.db.html">Zend_Test_PHPUnit_Db</a></div>
                    </td>
                </tr>
            </table>
<hr />
<div id="zend.test.phpunit" class="section"><div class="info"><h1 class="title">Zend_Test_PHPUnit</h1></div>
    

    <p class="para">
        <span class="classname">Zend_Test_PHPUnit</span> provides a TestCase for <acronym class="acronym">MVC</acronym>
        applications that contains assertions for testing against a variety of
        responsibilities. Probably the easiest way to understand what it can do
        is to see an example.
    </p>

    <div class="example" id="zend.test.phpunit.loginexample"><div class="info"><p><b>Example #1 Application Login TestCase example</b></p></div>
        

        <div class="example-contents"><p>
            The following is a simple test case for a
            <span class="classname">UserController</span> to verify several things:
        </p></div>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                    The login form should be displayed to non-authenticated users.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    When a user logs in, they should be redirected to their profile
                    page, and that profile page should show relevant information.
                </p>
            </li>
        </ul>

        <div class="example-contents"><p>
            This particular example assumes a few things. First, we&#039;re moving
            most of our bootstrapping to a plugin. This simplifies setup of the
            test case as it allows us to specify our environment succinctly,
            and also allows us to bootstrap the application in a single line.
            Also, our particular example is assuming that autoloading is setup
            so we do not need to worry about requiring the appropriate classes
            (such as the correct controller, plugin, etc).
        </p></div>

        <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        $this-&gt;bootstrap = array($this, &#039;appBootstrap&#039;);
        parent::setUp();
    }

    public function appBootstrap()
    {
        $this-&gt;frontController
             -&gt;registerPlugin(new Bugapp_Plugin_Initialize(&#039;development&#039;));
    }

    public function testCallWithoutActionShouldPullFromIndexAction()
    {
        $this-&gt;dispatch(&#039;/user&#039;);
        $this-&gt;assertController(&#039;user&#039;);
        $this-&gt;assertAction(&#039;index&#039;);
    }

    public function testIndexActionShouldContainLoginForm()
    {
        $this-&gt;dispatch(&#039;/user&#039;);
        $this-&gt;assertAction(&#039;index&#039;);
        $this-&gt;assertQueryCount(&#039;form#loginForm&#039;, 1);
    }

    public function testValidLoginShouldGoToProfilePage()
    {
        $this-&gt;request-&gt;setMethod(&#039;POST&#039;)
              -&gt;setPost(array(
                  &#039;username&#039; =&gt; &#039;foobar&#039;,
                  &#039;password&#039; =&gt; &#039;foobar&#039;
              ));
        $this-&gt;dispatch(&#039;/user/login&#039;);
        $this-&gt;assertRedirectTo(&#039;/user/view&#039;);

        $this-&gt;resetRequest()
             -&gt;resetResponse();

        $this-&gt;request-&gt;setMethod(&#039;GET&#039;)
             -&gt;setPost(array());
        $this-&gt;dispatch(&#039;/user/view&#039;);
        $this-&gt;assertRoute(&#039;default&#039;);
        $this-&gt;assertModule(&#039;default&#039;);
        $this-&gt;assertController(&#039;user&#039;);
        $this-&gt;assertAction(&#039;view&#039;);
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQuery(&#039;dl&#039;);
        $this-&gt;assertQueryContentContains(&#039;h2&#039;, &#039;User: foobar&#039;);
    }
}
</pre>


        <div class="example-contents"><p>
            This example could be written somewhat simpler -- not all the
            assertions shown are necessary, and are provided for illustration
            purposes only. Hopefully, it shows how simple it can be to test
            your applications.
        </p></div>
    </div>

    <div class="section" id="zend.test.phpunit.bootstrapping"><div class="info"><h1 class="title">Bootstrapping your TestCase</h1></div>
    

    <p class="para">
        As noted in the <a href="zend.test.phpunit.html#zend.test.phpunit.loginexample" class="link">Login
            example</a>, all <acronym class="acronym">MVC</acronym> test cases should extend
        <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span>. This class in turn
        extends <span class="classname">PHPUnit_Framework_TestCase</span>, and gives you all the
        structure and assertions you&#039;d expect from PHPUnit -- as well as some
        scaffolding and assertions specific to Zend Framework&#039;s <acronym class="acronym">MVC</acronym>
        implementation.
    </p>

    <p class="para">
        In order to test your <acronym class="acronym">MVC</acronym> application, you will need to bootstrap it.
        There are several ways to do this, all of which hinge on the public
        <var class="varname">$bootstrap</var> property.
    </p>

    <p class="para">
        First, and probably most straight-forward, simply create a
        <span class="classname">Zend_Application</span> instance as you would in your
        <var class="filename">index.php</var>, and assign it to the <var class="varname">$bootstrap</var> property.
        Typically, you will do this in your  <span class="methodname">setUp()</span> method; you will need
        to call  <span class="methodname">parent::setUp()</span> when done:
    </p>

    <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        // Assign and instantiate in one step:
        $this-&gt;bootstrap = new Zend_Application(
            &#039;testing&#039;,
            APPLICATION_PATH . &#039;/configs/application.ini&#039;
        );
        parent::setUp();
    }
}
</pre>


    <p class="para">
        Second, you can set this property to point to a file. If you do
        this, the file should <em class="emphasis">not</em> dispatch the front
        controller, but merely setup the front controller and any application
        specific needs.
    </p>

    <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $bootstrap = &#039;/path/to/bootstrap/file.php&#039;

    // ...
}
</pre>


    <p class="para">
        Third, you can provide a <acronym class="acronym">PHP</acronym> callback to execute in order to bootstrap
        your application. This method is seen in the <a href="zend.test.phpunit.html#zend.test.phpunit.loginexample" class="link">Login example</a>. If
        the callback is a function or static method, this could be set at the
        class level:
    </p>

    <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $bootstrap = array(&#039;App&#039;, &#039;bootstrap&#039;);

    // ...
}
</pre>


    <p class="para">
        In cases where an object instance is necessary, we recommend performing
        this in your  <span class="methodname">setUp()</span> method:
    </p>

    <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        // Use the &#039;start&#039; method of a Bootstrap object instance:
        $bootstrap = new Bootstrap(&#039;test&#039;);
        $this-&gt;bootstrap = array($bootstrap, &#039;start&#039;);
        parent::setUp();
    }
}
</pre>


    <p class="para">
        Note the call to  <span class="methodname">parent::setUp()</span>; this is necessary, as
        the  <span class="methodname">setUp()</span> method of
        <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span> will perform the
        remainder of the bootstrapping process (which includes calling the
        callback).
    </p>

    <p class="para">
        During normal operation, the  <span class="methodname">setUp()</span> method will bootstrap
        the application. This process first will include cleaning up the
        environment to a clean request state, resetting any plugins and
        helpers, resetting the front controller instance, and creating new
        request and response objects. Once this is done, it will then either
         <span class="methodname">include()</span> the file specified in <var class="varname">$bootstrap</var>, or
        call the callback specified.
    </p>

    <p class="para">
        Bootstrapping should be as close as possible to how the application
        will be bootstrapped. However, there are several caveats:
    </p>

    <ul class="itemizedlist">
        <li class="listitem">
            <p class="para">
                Do not provide alternate implementations of the Request and
                Response objects; they will not be used.
                <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span> uses custom
                request and response objects,
                <span class="classname">Zend_Controller_Request_HttpTestCase</span> and
                <span class="classname">Zend_Controller_Response_HttpTestCase</span>, respectively.
                These objects provide methods for setting up the request
                environment in targeted ways, and pulling response artifacts in
                specific ways.
            </p>
        </li>

        <li class="listitem">
            <p class="para">
                Do not expect to test server specifics. In other words, the tests
                are not a guarantee that the code will run on a specific server
                configuration, but merely that the application should run as
                expected should the router be able to route the given request. To
                this end, do not set server-specific headers in the request object.
            </p>
        </li>
    </ul>

    <p class="para">
        Once the application is bootstrapped, you can then start creating
        your tests.
    </p>
</div>
    <div class="section" id="zend.test.phpunit.testing"><div class="info"><h1 class="title">Testing your Controllers and MVC Applications</h1></div>
    

    <p class="para">
        Once you have your bootstrap in place, you can begin testing. Testing
        is basically as you would expect in an PHPUnit test suite, with a few
        minor differences.
    </p>

    <p class="para">
        First, you will need to dispatch a <acronym class="acronym">URL</acronym> to test, using the
         <span class="methodname">dispatch()</span> method of the TestCase:
    </p>

    <pre class="programlisting brush: php">
class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // ...

    public function testHomePage()
    {
        $this-&gt;dispatch(&#039;/&#039;);
        // ...
    }
}
</pre>


    <p class="para">
        There will be times, however, that you need to provide extra
        information -- <b><tt>GET</tt></b> and POST variables, COOKIE information, etc. You can
        populate the request with that information:
    </p>

    <pre class="programlisting brush: php">
class FooControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // ...

    public function testBarActionShouldReceiveAllParameters()
    {
        // Set GET variables:
        $this-&gt;request-&gt;setQuery(array(
            &#039;foo&#039; =&gt; &#039;bar&#039;,
            &#039;bar&#039; =&gt; &#039;baz&#039;,
        ));

        // Set POST variables:
        $this-&gt;request-&gt;setPost(array(
            &#039;baz&#039;  =&gt; &#039;bat&#039;,
            &#039;lame&#039; =&gt; &#039;bogus&#039;,
        ));

        // Set a cookie value:
        $this-&gt;request-&gt;setCookie(&#039;user&#039;, &#039;matthew&#039;);
        // or many:
        $this-&gt;request-&gt;setCookies(array(
            &#039;timestamp&#039; =&gt; time(),
            &#039;host&#039;      =&gt; &#039;foobar&#039;,
        ));

        // Set headers, even:
        $this-&gt;request-&gt;setHeader(&#039;X-Requested-With&#039;, &#039;XmlHttpRequest&#039;);

        // Set the request method:
        $this-&gt;request-&gt;setMethod(&#039;POST&#039;);

        // Dispatch:
        $this-&gt;dispatch(&#039;/foo/bar&#039;);

        // ...
    }
}
</pre>


    <p class="para">
        Now that the request is made, it&#039;s time to start making assertions against it.
    </p>

    <div class="section" id="zend.test.phpunit.testing.redirector"><div class="info"><h1 class="title">Controller Tests and the Redirector Action Helper</h1></div>
        

        <div class="important"><b class="important">Important</b>
            <p class="para">
                The redirect action helper issues an  <span class="methodname">exit()</span> statement
                when using the method  <span class="methodname">gotoAndExit()</span>
                and will then obviously also stops a test running for this method.
                For testability of your application dont use that method on the
                redirector!
            </p>
        </div>

        <p class="para">
            Due to its nature the redirector action helper plugin issues a redirect
            and exists after this. Because you cannot test parts of an application
            that issue exit calls <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span>
            automatically disables the exit part of the redirector which can cause
            different behaviours in tests and the real application. To make sure
            redirect work correctly you should it them in the following way:
        </p>

        <pre class="programlisting brush: php">
class MyController extends Zend_Controller_Action
{
    public function indexAction()
    {
        if($someCondition == true) {
            return $this-&gt;_redirect(...);
        } else if($anotherCondition == true) {
            $this-&gt;_redirector-&gt;gotoSimple(&quot;foo&quot;);
            return;
        }

        // do some stuff here
    }
}
</pre>


        <div class="important"><b class="important">Important</b>
            <p class="para">
                Depending on your application this is not enough as additional action,
                 <span class="methodname">preDispatch()</span> or  <span class="methodname">postDispatch()</span>
                logic might be executed. This cannot be handled in a good way with Zend Test
                currently.
            </p>
        </div>
    </div>
</div>
    <div class="section" id="zend.test.phpunit.assertions"><div class="info"><h1 class="title">Assertions</h1></div>
    

    <p class="para">
        Assertions are at the heart of Unit Testing; you use them to verify
        that the results are what you expect. To this end,
        <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span> provides a number of
        assertions to make testing your <acronym class="acronym">MVC</acronym> apps and controllers simpler.
    </p>

    <div class="section" id="zend.test.phpunit.assertions.query"><div class="info"><h1 class="title">CSS Selector Assertions</h1></div>
        

        <p class="para">
            <acronym class="acronym">CSS</acronym> selectors are an easy way to verify that certain artifacts are
            present in the response content. They also make it trivial to
            ensure that items necessary for Javascript UIs and/or <acronym class="acronym">AJAX</acronym>
            integration will be present; most JS toolkits provide some
            mechanism for pulling DOM elements based on <acronym class="acronym">CSS</acronym> selectors, so the
            syntax would be the same.
        </p>

        <p class="para">
            This functionality is provided via <a href="zend.dom.query.html" class="link">Zend_Dom_Query</a>, and integrated
            into a set of &#039;Query&#039; assertions. Each of these assertions takes
            as their first argument a <acronym class="acronym">CSS</acronym> selector, with optionally additional
            arguments and/or an error message, based on the assertion type. You
            can find the rules for writing the <acronym class="acronym">CSS</acronym> selectors in the <a href="zend.dom.query.html#zend.dom.query.operation" class="link">Zend_Dom_Query theory of
                operation chapter</a>. Query assertions include:
        </p>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertQuery($path, $message)</span>: assert that
                    one or more DOM elements matching the given <acronym class="acronym">CSS</acronym> selector are
                    present. If a <var class="varname">$message</var> is present, it will be
                    prepended to any failed assertion message.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertQueryContentContains($path, $match, $message)</span>:
                    assert that one or more DOM elements matching the given <acronym class="acronym">CSS</acronym>
                    selector are present, and that at least one contains the content provided in
                    <var class="varname">$match</var>. If a <var class="varname">$message</var> is present, it will
                    be prepended to any failed assertion message.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertQueryContentRegex($path, $pattern, $message)</span>:
                    assert that one or more DOM elements matching the given <acronym class="acronym">CSS</acronym>
                    selector are present, and that at least one matches the regular expression
                    provided in <var class="varname">$pattern</var>. If a <var class="varname">$message</var> is
                    present, it will be prepended to any failed assertion message.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertQueryCount($path, $count, $message)</span>: assert that
                    there are exactly <var class="varname">$count</var> DOM elements matching the given
                    <acronym class="acronym">CSS</acronym> selector present. If a <var class="varname">$message</var> is
                    present, it will be prepended to any failed assertion message.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertQueryCountMin($path, $count, $message)</span>: assert
                    that there are at least <var class="varname">$count</var> DOM elements matching the
                    given <acronym class="acronym">CSS</acronym> selector present. If a <var class="varname">$message</var>
                    is present, it will be prepended to any failed assertion message.
                    <em class="emphasis">Note:</em> specifying a value of 1 for
                    <var class="varname">$count</var> is the same as simply using
                     <span class="methodname">assertQuery()</span>.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertQueryCountMax($path, $count, $message)</span>: assert
                    that there are no more than <var class="varname">$count</var> DOM elements matching the
                    given <acronym class="acronym">CSS</acronym> selector present. If a <var class="varname">$message</var>
                    is present, it will be prepended to any failed assertion message.
                    <em class="emphasis">Note:</em> specifying a value of 1 for
                    <var class="varname">$count</var> is the same as simply using
                     <span class="methodname">assertQuery()</span>.
                </p>
            </li>
        </ul>

        <p class="para">
            Additionally, each of the above has a &#039;Not&#039; variant that provides a
            negative assertion:  <span class="methodname">assertNotQuery()</span>,
             <span class="methodname">assertNotQueryContentContains()</span>,
             <span class="methodname">assertNotQueryContentRegex()</span>, and
             <span class="methodname">assertNotQueryCount()</span>. (Note that the min and
            max counts do not have these variants, for what should be obvious
            reasons.)
        </p>
    </div>

    <div class="section" id="zend.test.phpunit.assertions.xpath"><div class="info"><h1 class="title">XPath Assertions</h1></div>
        

        <p class="para">
            Some developers are more familiar with XPath than with <acronym class="acronym">CSS</acronym>
            selectors, and thus XPath variants of all the <a href="zend.test.phpunit.html#zend.test.phpunit.assertions.query" class="link">Query
                assertions</a> are also provided. These are:
        </p>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertXpath($path, $message = &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotXpath($path, $message = &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertXpathContentContains($path, $match, $message =
                        &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotXpathContentContains($path, $match, $message =
                        &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertXpathContentRegex($path, $pattern, $message = &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotXpathContentRegex($path, $pattern, $message =
                        &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertXpathCount($path, $count, $message = &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotXpathCount($path, $count, $message = &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertXpathCountMin($path, $count, $message = &#039;&#039;)</span>
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotXpathCountMax($path, $count, $message = &#039;&#039;)</span>
                </p>
            </li>
        </ul>
    </div>

    <div class="section" id="zend.test.phpunit.assertions.redirect"><div class="info"><h1 class="title">Redirect Assertions</h1></div>
        

        <p class="para">
            Often an action will redirect. Instead of following the redirect,
            <span class="classname">Zend_Test_PHPUnit_ControllerTestCase</span> allows you to
            test for redirects with a handful of assertions.
        </p>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertRedirect($message = &#039;&#039;)</span>: assert simply that
                    a redirect has occurred.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotRedirect($message = &#039;&#039;)</span>: assert that no
                    redirect has occurred.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertRedirectTo($url, $message = &#039;&#039;)</span>: assert that
                    a redirect has occurred, and that the value of the Location
                    header is the <var class="varname">$url</var> provided.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotRedirectTo($url, $message = &#039;&#039;)</span>: assert that
                    a redirect has either NOT occurred, or that the value of the Location
                    header is NOT the <var class="varname">$url</var> provided.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertRedirectRegex($pattern, $message = &#039;&#039;)</span>:
                    assert that a redirect has occurred, and that the value of the
                    Location header matches the regular expression provided by
                    <var class="varname">$pattern</var>.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertNotRedirectRegex($pattern, $message = &#039;&#039;)</span>:
                    assert that a redirect has either NOT occurred, or that the value of the
                    Location header does NOT match the regular expression provided by
                    <var class="varname">$pattern</var>.
                </p>
            </li>
        </ul>
    </div>

    <div class="section" id="zend.test.phpunit.assertions.header"><div class="info"><h1 class="title">Response Header Assertions</h1></div>
        

        <p class="para">
            In addition to checking for redirect headers, you will often need
            to check for specific <acronym class="acronym">HTTP</acronym> response codes and headers -- for
            instance, to determine whether an action results in a 404 or 500
            response, or to ensure that <acronym class="acronym">JSON</acronym> responses contain the appropriate
            Content-Type header. The following assertions are available.
        </p>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertResponseCode($code, $message = &#039;&#039;)</span>: assert
                    that the response resulted in the given <acronym class="acronym">HTTP</acronym> response code.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertHeader($header, $message = &#039;&#039;)</span>: assert
                    that the response contains the given header.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertHeaderContains($header, $match, $message)</span>: assert
                    that the response contains the given header and that its content contains the
                    given string.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertHeaderRegex($header, $pattern, $message)</span>: assert
                    that the response contains the given header and that its content matches the
                    given regex.
                </p>
            </li>
        </ul>

        <p class="para">
            Additionally, each of the above assertions have a &#039;Not&#039; variant for
            negative assertions.
        </p>
    </div>

    <div class="section" id="zend.test.phpunit.assertions.request"><div class="info"><h1 class="title">Request Assertions</h1></div>
        

        <p class="para">
            It&#039;s often useful to assert against the last run action,
            controller, and module; additionally, you may want to assert
            against the route that was matched. The following assertions can
            help you in this regard:
        </p>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertModule($module, $message = &#039;&#039;)</span>: Assert that
                    the given module was used in the last dispatched action.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertController($controller, $message = &#039;&#039;)</span>:
                    Assert that the given controller was selected in the last
                    dispatched action.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertAction($action, $message = &#039;&#039;)</span>: Assert that
                    the given action was last dispatched.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                     <span class="methodname">assertRoute($route, $message = &#039;&#039;)</span>: Assert that
                    the given named route was matched by the router.
                </p>
            </li>
        </ul>

        <p class="para">
            Each also has a &#039;Not&#039; variant for negative assertions.
        </p>
    </div>
</div>
    <div class="section" id="zend.test.phpunit.examples"><div class="info"><h1 class="title">Examples</h1></div>
    

    <p class="para">
        Knowing how to setup your testing infrastructure and how to make
        assertions is only half the battle; now it&#039;s time to start looking at
        some actual testing scenarios to see how you can leverage them.
    </p>

    <div class="example" id="zend.test.phpunit.examples.userController"><div class="info"><p><b>Example #2 Testing a UserController</b></p></div>
        

        <div class="example-contents"><p>
            Let&#039;s consider a standard task for a website: authenticating and registering users. In
            our example, we&#039;ll define a UserController for handling this, and have the following
            requirements:
        </p></div>

        <ul class="itemizedlist">
            <li class="listitem">
                <p class="para">
                    If a user is not authenticated, they will always be redirected
                    to the login page of the controller, regardless of the action
                    specified.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    The login form page will show both the login form and the
                    registration form.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    Providing invalid credentials should result in returning to the login form.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    Valid credentials should result in redirecting to the user profile page.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    The profile page should be customized to contain the user&#039;s username.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    Authenticated users who visit the login page should be
                    redirected to their profile page.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    On logout, a user should be redirected to the login page.
                </p>
            </li>

            <li class="listitem">
                <p class="para">
                    With invalid data, registration should fail.
                </p>
            </li>
        </ul>

        <div class="example-contents"><p>
            We could, and should define further tests, but these will do for
            now.
        </p></div>

        <div class="example-contents"><p>
            For our application, we will define a plugin, &#039;Initialize&#039;, that
            runs at  <span class="methodname">routeStartup()</span>. This allows us to encapsulate
            our bootstrap in an OOP interface, which also provides an easy way
            to provide a callback. Let&#039;s look at the basics of this class
            first:
        </p></div>

        <pre class="programlisting brush: php">
class Bugapp_Plugin_Initialize extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Config
     */
    protected static $_config;

    /**
     * @var string Current environment
     */
    protected $_env;

    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * @var string Path to application root
     */
    protected $_root;

    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     *
     * @param  string $env
     * @param  string|null $root
     * @return void
     */
    public function __construct($env, $root = null)
    {
        $this-&gt;_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . &#039;/../../../&#039;);
        }
        $this-&gt;_root = $root;

        $this-&gt;initPhpConfig();

        $this-&gt;_front = Zend_Controller_Front::getInstance();
    }

    /**
     * Route startup
     *
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $this-&gt;initDb();
        $this-&gt;initHelpers();
        $this-&gt;initView();
        $this-&gt;initPlugins();
        $this-&gt;initRoutes();
        $this-&gt;initControllers();
    }

    // definition of methods would follow...
}
</pre>


        <div class="example-contents"><p>
            This allows us to create a bootstrap callback like the following:
        </p></div>

        <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function appBootstrap()
    {
        $controller = $this-&gt;getFrontController();
        $controller-&gt;registerPlugin(
            new Bugapp_Plugin_Initialize(&#039;development&#039;)
        );
    }

    public function setUp()
    {
        $this-&gt;bootstrap = array($this, &#039;appBootstrap&#039;);
        parent::setUp();
    }

    // ...
}
</pre>


        <div class="example-contents"><p>
            Once we have that in place, we can write our tests. However, what
            about those tests that require a user is logged in? The easy
            solution is to use our application logic to do so... and fudge a
            little by using the  <span class="methodname">resetRequest()</span> and
             <span class="methodname">resetResponse()</span> methods, which will allow us to
            dispatch another request.
        </p></div>

        <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // ...

    public function loginUser($user, $password)
    {
        $this-&gt;request-&gt;setMethod(&#039;POST&#039;)
                      -&gt;setPost(array(
                          &#039;username&#039; =&gt; $user,
                          &#039;password&#039; =&gt; $password,
                      ));
        $this-&gt;dispatch(&#039;/user/login&#039;);
        $this-&gt;assertRedirectTo(&#039;/user/view&#039;);

        $this-&gt;resetRequest()
             -&gt;resetResponse();

        $this-&gt;request-&gt;setPost(array());

        // ...
    }

    // ...
}
</pre>


        <div class="example-contents"><p>
            Now let&#039;s write tests:
        </p></div>

        <pre class="programlisting brush: php">
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    // ...

    public function testCallWithoutActionShouldPullFromIndexAction()
    {
        $this-&gt;dispatch(&#039;/user&#039;);
        $this-&gt;assertController(&#039;user&#039;);
        $this-&gt;assertAction(&#039;index&#039;);
    }

    public function testLoginFormShouldContainLoginAndRegistrationForms()
    {
        $this-&gt;dispatch(&#039;/user&#039;);
        $this-&gt;assertQueryCount(&#039;form&#039;, 2);
    }

    public function testInvalidCredentialsShouldResultInRedisplayOfLoginForm()
    {
        $request = $this-&gt;getRequest();
        $request-&gt;setMethod(&#039;POST&#039;)
                -&gt;setPost(array(
                    &#039;username&#039; =&gt; &#039;bogus&#039;,
                    &#039;password&#039; =&gt; &#039;reallyReallyBogus&#039;,
                ));
        $this-&gt;dispatch(&#039;/user/login&#039;);
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQuery(&#039;form&#039;);
    }

    public function testValidLoginShouldRedirectToProfilePage()
    {
        $this-&gt;loginUser(&#039;foobar&#039;, &#039;foobar&#039;);
    }

    public function testAuthenticatedUserShouldHaveCustomizedProfilePage()
    {
        $this-&gt;loginUser(&#039;foobar&#039;, &#039;foobar&#039;);
        $this-&gt;request-&gt;setMethod(&#039;GET&#039;);
        $this-&gt;dispatch(&#039;/user/view&#039;);
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQueryContentContains(&#039;h2&#039;, &#039;foobar&#039;);
    }

    public function
        testAuthenticatedUsersShouldBeRedirectedToProfileWhenVisitingLogin()
    {
        $this-&gt;loginUser(&#039;foobar&#039;, &#039;foobar&#039;);
        $this-&gt;request-&gt;setMethod(&#039;GET&#039;);
        $this-&gt;dispatch(&#039;/user&#039;);
        $this-&gt;assertRedirectTo(&#039;/user/view&#039;);
    }

    public function testUserShouldRedirectToLoginPageOnLogout()
    {
        $this-&gt;loginUser(&#039;foobar&#039;, &#039;foobar&#039;);
        $this-&gt;request-&gt;setMethod(&#039;GET&#039;);
        $this-&gt;dispatch(&#039;/user/logout&#039;);
        $this-&gt;assertRedirectTo(&#039;/user&#039;);
    }

    public function testRegistrationShouldFailWithInvalidData()
    {
        $data = array(
            &#039;username&#039; =&gt; &#039;This will not work&#039;,
            &#039;email&#039;    =&gt; &#039;this is an invalid email&#039;,
            &#039;password&#039; =&gt; &#039;Th1s!s!nv@l1d&#039;,
            &#039;passwordVerification&#039; =&gt; &#039;wrong!&#039;,
        );
        $request = $this-&gt;getRequest();
        $request-&gt;setMethod(&#039;POST&#039;)
                -&gt;setPost($data);
        $this-&gt;dispatch(&#039;/user/register&#039;);
        $this-&gt;assertNotRedirect();
        $this-&gt;assertQuery(&#039;form .errors&#039;);
    }
}
</pre>


        <div class="example-contents"><p>
            Notice that these are terse, and, for the most part, don&#039;t look for
            actual content. Instead, they look for artifacts within the
            response -- response codes and headers, and DOM nodes. This allows
            you to verify that the structure is as expected -- preventing your
            tests from choking every time new content is added to the site.
        </p></div>

        <div class="example-contents"><p>
            Also notice that we use the structure of the document in our tests.
            For instance, in the final test, we look for a form that has a node
            with the class of &quot;errors&quot;; this allows us to test merely for the
            presence of form validation errors, and not worry about what
            specific errors might have been thrown.
        </p></div>

        <div class="example-contents"><p>
            This application <em class="emphasis">may</em> utilize a database. If
            so, you will probably need some scaffolding to ensure that the
            database is in a pristine, testable configuration at the beginning
            of each test. PHPUnit already provides functionality for doing so;
            <a href="http://www.phpunit.de/manual/3.4/en/database.html" class="link external">&raquo; read
                about it in the PHPUnit documentation</a>. We recommend
            using a separate database for testing versus production, and in
            particular recommend using either a SQLite file or in-memory
            database, as both options perform very well, do not require a
            separate server, and can utilize most <acronym class="acronym">SQL</acronym> syntax.
        </p></div>
    </div>
</div>
</div>
        <hr />

            <table width="100%">
                <tr>
                    <td width="25%" style="text-align: left;">
                    <a href="zend.test.introduction.html">Introduction</a>
                    </td>

                    <td width="50%" style="text-align: center;">
                        <div class="up"><span class="up"><a href="zend.test.html">Zend_Test</a></span><br />
                        <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div>
                    </td>

                    <td width="25%" style="text-align: right;">
                        <div class="next" style="text-align: right; float: right;"><a href="zend.test.phpunit.db.html">Zend_Test_PHPUnit_Db</a></div>
                    </td>
                </tr>
            </table>
</td>
        <td style="font-size: smaller;" width="15%"> <style type="text/css">
#leftbar {
	float: left;
	width: 186px;
	padding: 5px;
	font-size: smaller;
}
ul.toc {
	margin: 0px 5px 5px 5px;
	padding: 0px;
}
ul.toc li {
	font-size: 85%;
	margin: 1px 0 1px 1px;
	padding: 1px 0 1px 11px;
	list-style-type: none;
	background-repeat: no-repeat;
	background-position: center left;
}
ul.toc li.header {
	font-size: 115%;
	padding: 5px 0px 5px 11px;
	border-bottom: 1px solid #cccccc;
	margin-bottom: 5px;
}
ul.toc li.active {
	font-weight: bold;
}
ul.toc li a {
	text-decoration: none;
}
ul.toc li a:hover {
	text-decoration: underline;
}
</style>
 <ul class="toc">
  <li class="header home"><a href="manual.html">Programmer's Reference Guide</a></li>
  <li class="header up"><a href="manual.html">Programmer's Reference Guide</a></li>
  <li class="header up"><a href="reference.html">Zend Framework Reference</a></li>
  <li class="header up"><a href="zend.test.html">Zend_Test</a></li>
  <li><a href="zend.test.introduction.html">Introduction</a></li>
  <li class="active"><a href="zend.test.phpunit.html">Zend_Test_PHPUnit</a></li>
  <li><a href="zend.test.phpunit.db.html">Zend_Test_PHPUnit_Db</a></li>
 </ul>
 </td>
    </tr>
</table>

<script type="text/javascript" src="../js/shCore.js"></script>
<script type="text/javascript" src="../js/shAutoloader.js"></script>
<script type="text/javascript" src="../js/main.js"></script>

</body>
</html>